package cn.czg.cms.service.impl;

import cn.czg.cms.entity.Post;
import cn.czg.cms.entity.dto.PostDTO;
import cn.czg.cms.entity.dto.PostWithUser;
import cn.czg.cms.entity.req.PostCreateRequest;
import cn.czg.cms.mapper.PostMapper;
import cn.czg.cms.service.PostService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {

    private final PostMapper postMapper;

    private final ObjectMapper objectMapper;


    public PostServiceImpl(PostMapper postMapper, ObjectMapper objectMapper) {
        this.postMapper = postMapper;
        this.objectMapper = objectMapper;
    }

    @Override
    public IPage<PostDTO> pageList(Double lng, Double lat, String order, String type, int pageNum, int pageSize, String searchKey) {
        Page<PostDTO> page = new Page<>(pageNum, pageSize);
        return postMapper.selectPostsByLocation(page, lng, lat, order, type, searchKey);
    }

    @Override
    public void updateLikeCount(String postId, int like) {
        postMapper.updateLikeCount(postId, like);

    }

    @Override
    public int createPost(PostCreateRequest request) {
        Post post = new Post();

        post.setUserId(request.getUserId());
        post.setType(request.getType());
        post.setTitle(request.getTitle());
        post.setContent(request.getContent());
        post.setImages(serializeImages(request.getImages()));
        post.setLocation(request.getLocation());
        post.setTags(request.getTags());
        post.setLatitude(request.getLatitude());
        post.setLongitude(request.getLongitude());
        post.setStatus(1); // 默认正常
        post.setCreatedAt(LocalDateTime.now());
        post.setUpdatedAt(LocalDateTime.now());
        return postMapper.insert(post);
    }

    private String serializeImages(java.util.List<String> images) {
        try {
            return objectMapper.writeValueAsString(images);
        } catch (Exception e) {
            throw new RuntimeException("图片序列化失败", e);
        }
    }

    @Override
    public IPage<PostWithUser> listByUser(Long userId, int pageNum, int pageSize) {
        Page<PostWithUser> page = new Page<>(pageNum, pageSize);
        return postMapper.selectPageWithUser(page, userId);
    }

    @Override
    public PostWithUser detail(String id) {
        return postMapper.detail(id);
    }
}
